<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/17
 * Time: 下午5:21
 */

namespace app\common\model;
//use JPush\Client;
use think\Db;
use think\Session;
use JPush\Client;
class Message extends Common
{
    /**
     * 极光推送
     *
     * @param string $message 消息内容
     * @param array $extra 额外数据
     * @param array $user 用户
     * @throws ServerException
     */
    public static  function jPush($message, $user = array(),$extra=array())
    {
        //初始化JPush客户端
        $client = new Client(config('jpush')["app_key"], config('jpush')["app_secret"]);

        //生成推送
        $push = $client->push();

        //设置推送平台
        $push->setPlatform("all");

        //设置推送目标
        if (empty($user))
        {
            return;
        }
        elseif($user=="all")
        {
            $push->addAllAudience();
        }else{
            //            if (is_array($user))
//            {
//                $user = implode(",", $user);
//            }
            /*设备id推送*/
            $push->addRegistrationId($user);
        }

        $push->iosNotification($message, array("extras" => $extra))
            ->androidNotification($message, array("extras" => $extra));
        // $push->message($message, array("extras" => $extra));


        //发送推送报文
        try
        {
            $push->send();
        }
        catch (\Exception $exception)
        {
//            throw new ServerException($exception->getMessage());
        }
    }


    /**
     * 消息列表
     * @param $user_id
     * @param int $page
     * @param int $pagesize
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function noticeList($user_id,$page=1,$pagesize=10)
    {
        if(empty($user_id))
        {
            //未登录
            $list=Db::name('notice')
                ->where('is_visible',1)
                ->where('type',1)
                ->order('display_order desc,id desc')
                ->page($page,$pagesize)
                ->field('title,description,0 as status,create_time,id as _id')
                ->select();
            foreach ($list as $key=>$item){
                $list[$key]['create_time'] = friend_date($item['create_time']);
            }
        }else{
            $list=Db::name('notice')
                ->alias('no')
                ->join('__NOTICE_READER__ nr','nr.uid='.$user_id.' AND nr.nid=no.id','LEFT')
                ->where('no.uid','in',[0,$user_id])
                ->where('no.is_visible',1)
                ->order('no.display_order desc,no.id desc')
                ->field('no.title,no.description,no.create_time,nr.id as reader_id,no.id as _id')
                ->page($page,$pagesize)
                ->select();
            foreach ($list as $key=>$item){
                if($item['reader_id']>0){
                    $list[$key]['status'] = 1;
                }else{
                    $list[$key]['status'] = 0;
                }
                $list[$key]['create_time'] = friend_date($item['create_time']);
                unset($list[$key]['reader_id']);
            }
        }

        return empty($list)?array():$list;
    }

    /**
     * 公告详情
     * @param $user_id
     * @param $notice_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws TokenException
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function noticeInfo($user_id,$notice_id)
    {
        $info=Db::name('notice')
            ->alias('no')
            ->join('__NOTICE_DETAIL__ nd','nd.id=no.detail_id','LEFT')
            ->where('no.id',$notice_id)
            ->where('no.is_visible',1)
            ->field('no.id,no.type,no.uid,no.title,nd.detail,no.create_time')
            ->find();

        if(!$info){
            throw new UserException('不存在此消息');
        }
        if(!empty($user_id)){
            //登录记录阅读记录
            $reader = Db::name('notice_reader')
                ->where('uid',$user_id)
                ->where('nid',$info['id'])
                ->find();
            if(!$reader){
                $data = [
                    'create_time'=>now_datetime(),
                    'uid'=>$user_id,
                    'nid'=>$info['id']
                ];
                Db::name('notice_reader')->insert($data);
            }
        }
        unset($info['id']);
        unset($info['type']);
        unset($info['uid']);
        $info['create_time'] = friend_date($info['create_time']);
        return empty($info)?array():$info;
    }

    /**
     *公告未读数量
     * @param $userid
     * @return int|string
     * @throws \think\Exception
     */
    static public function noticeNum($userid){
        $all = Db::name('notice')
            ->where('uid','in','0,'.$userid)
            ->count();
        $reader = Db::name('notice_reader')->where('uid',$userid)->count();
        $num = $all-$reader;
        $num = $num<0 ? 0 : $num;
        return $num;
    }


    /**
     * 后台操作log
     * @param int $uid
     * @param int $money
     * @param int $type 1:总后台，2：商家后台
     * @param string $extra
     */

    static public function admin_log($uid=0,$extra,$money=0,$type=1){
        if($type==1)
        {
            $admin = Session::get('H_ADMIN_LOGIN_USER');
        }else{
            $admin = Session::get('H_BUSINESS_LOGIN_USER');
        }

        $data = [
            'admin_id'=>$admin['id'],
            'user_id'=>$uid,
            'content'=>$extra,
            'money'=>$money,
            'create_time'=>time(),
            'user_name'=>$admin['username']
        ];
        Db::name('admin_log')->insert($data);
    }
    static public function userNotice($title,$text,$uid){
        $detail_id = Db::name('notice_detail')->insertGetId(['detail'=>$text]);
        $notice['title']=$title;
        $notice['description']=$title;
        $notice['type']="2";
        $notice['detail_id'] = $detail_id;
        $notice['uid']=$uid;
        $notice['is_visible']=1;
        $notice['create_time']=time();
        $notice['update_time']=time();
        Db::name('notice')->insert($notice);
    }
}
